package com.zzptc.sky.translate.Fragment;

import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.zzptc.sky.translate.MyApplication;
import com.zzptc.sky.translate.R;
import com.zzptc.sky.translate.ben.Entries;

import java.util.List;

/**
 * Created by Administrator on 2017/10/20.
 */

public class TheWordFragment extends Fragment {

    ListView listView;
    static List<Entries> list;
    static Adapter adapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
       View view=View.inflate(getActivity(),R.layout.activity_the_word,null);
        listView = (ListView) view.findViewById(R.id.listView_word);
        //TODO 通过GreenDao查询数据库的所有内容
        list = MyApplication.getInstances().getDaoSession().getEntriesDao().loadAll();
        //TODO  设置设配器
        adapter = new Adapter();
        listView.setAdapter(adapter);
        return view;
    }

    //TODO   暴露给外部的刷新方法
    //在修改适配器绑定的数组后，不用重新刷新Activity，通知Activity更新ListView
    public static void notifyDataSetChanged(){
        Log.e("<-->", "notify");
        //查询前清空list内容
        list.clear();
        //再次查询数据库所有内容
        list = MyApplication.getInstances().getDaoSession().getEntriesDao().loadAll();
        //刷新listView
        adapter.notifyDataSetChanged();
    }
//TODO 填充适配器
    class Adapter extends BaseAdapter {

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Entries d = list.get(position);
//TODO convertView为空时  显示list_item
            if (convertView == null){
                convertView = getActivity().getLayoutInflater().inflate(R.layout.list_item,null);
            }
            //不为空时  将内容按这种方式显示出来
            TextView tete1 = (TextView) convertView.findViewById(R.id.tete1),
                    tete2 = (TextView) convertView.findViewById(R.id.tete2);
            tete1.setText(""+d.getEntry());
            tete2.setText(""+d.getExplain());
            return convertView;
        }
    }
}
